package com.grm.service;

import com.grm.entity.MailDTO;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;

/**
 * @author crush
 * 邮箱发送实现类
 */
@Service
public class MailServiceImpl2 implements MailService2 {

    @Override
    public void send(MailDTO mailDTO) {

        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setDefaultEncoding("UTF-8");
        mailSender.setHost(mailDTO.getHost());
        mailSender.setPort(mailDTO.getPort());
        mailSender.setProtocol("smtp");
        mailSender.setUsername(mailDTO.getFromUser());
        mailSender.setPassword(mailDTO.getFromUserPassword());


        //创建一个SimpleMailMessage对象
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        //需要创建一个MimeMessageHelper对象，相关参数和简单邮件类似
        try {
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            //发件人
            helper.setFrom(mailSender.getUsername());
            //收件人 这个收件人可以是数组的，只是我这只需要单个 就没多做了。
            helper.setTo(mailDTO.getMail());
            helper.setSubject(mailDTO.getTitle());
            //将邮件内容设置为html格式
            // 发送
            helper.setText( mailDTO.getContent(), false);
            mailSender.send(mimeMessage);
        } catch (MessagingException e) {
            e.printStackTrace();
        }

    }
}

